package controller

import (
	"backEnd/common"
	"context"
	"fmt"
	"log"
	"net/http"
	"sync"

	"github.com/gin-gonic/gin"
	"github.com/tencentyun/cos-go-sdk-v5"
)

func UploadCoverImg(c *gin.Context) {
	//初始化cos云存储服务端
	client := common.InitClient()

	//文件属性
	opt := &cos.ObjectPutOptions{
		ObjectPutHeaderOptions: &cos.ObjectPutHeaderOptions{
			ContentType: "text/html",
		},
	}

	// 获取上传的文件
	from, err := c.MultipartForm()
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "获取表单数据失败"})
		return
	}
	files := from.File["files"]

	// 使用waitgroup来等待所有goroutine执行完毕
	var wg sync.WaitGroup
	wg.Add(len(files))

	for _, file := range files {
		// 将上传的文件直接上传到云存储
		fileContent, err := file.Open()
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": "打开文件失败"})
			return
		}
		defer fileContent.Close()

		_, err = client.Object.Put(context.Background(), file.Filename, fileContent, opt)
		if err != nil {
			log.Printf("上传文件到云存储失败: %s", err.Error())
		}

		fmt.Print("文件大小：", file.Size, "\n")
		wg.Done()
	}

	// 等待所有goroutine执行完毕
	
	wg.Wait()

	c.JSON(http.StatusCreated, gin.H{"msg": "图片上传成功！"})
}
